<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '商品',
  },
}
</route>

<script lang="ts" setup>
import type { CategoryItemDto } from '@/service/app'
import { getRect, isArray } from 'wot-design-uni/components/common/util'
import { BASE_URL } from '@/constants'
import { categoryControllerFindAll as getCategoryAPI } from '@/service/app'

// 获取屏幕边界到安全区域距离
let safeAreaInsets
let systemInfo

// #ifdef MP-WEIXIN
// 微信小程序使用新的API
systemInfo = uni.getWindowInfo()
safeAreaInsets = systemInfo.safeArea
  ? {
      top: systemInfo.safeArea.top,
      right: systemInfo.windowWidth - systemInfo.safeArea.right,
      bottom: systemInfo.windowHeight - systemInfo.safeArea.bottom,
      left: systemInfo.safeArea.left,
    }
  : null
// #endif

// #ifndef MP-WEIXIN
// 其他平台继续使用uni API
systemInfo = uni.getSystemInfoSync()
safeAreaInsets = systemInfo.safeAreaInsets
// #endif

// 定义子分类项的类型
interface SubCategory {
  title: string
  label: string
  price: string
}

// 定义分类项的类型
interface Category {
  label: string
  title: string
  picture: string
  items: SubCategory[]
}

const IMAGE_PLACEHOLDER = ''

const active = ref<number>(0)
const scrollTop = ref<number>(0)
const itemScrollTop = ref<number[]>([])
const backImg = ref<string>(IMAGE_PLACEHOLDER)

// 获取系统信息
const systemInfoSync = uni.getSystemInfoSync()
// 假设自定义导航栏高度为 0px
const navBarHeight = 200
// TODO: 计算偏移量
const offset = systemInfoSync.statusBarHeight + navBarHeight

const category = ref<CategoryItemDto[]>()

onLoad(async () => {
  const { data } = await getCategoryAPI({ params: {} })
  category.value = data
  backImg.value = BASE_URL + category.value[0]?.cover
  console.log(category.value)
  nextTick(() => {
    getRect('.category', true).then((rects) => {
      if (isArray(rects)) {
        itemScrollTop.value = rects.map(item => (item.top || 0) - rects[active.value].top)
        scrollTop.value = 0
      }
    })
  })
})

function handleChange({ value }) {
  active.value = value
  backImg.value = BASE_URL + category.value[value].cover
  scrollTop.value = itemScrollTop.value[value]
}
function onScroll(e) {
  const { scrollTop } = e.detail
  const threshold = 50 // 下一个标题与顶部的距离
  const index = itemScrollTop.value.findIndex(top => top > scrollTop && top - scrollTop <= threshold)
  if (index > -1) {
    active.value = index
    backImg.value = category.value[index]?.cover ? BASE_URL + category.value[index]?.cover : IMAGE_PLACEHOLDER
  }

  // 当距离顶部<10PX时候，左侧定位到第一个标签
  if (scrollTop < 10) {
    active.value = 0
  }

  // console.log(backImg.value)
}

// 商品点击事件
function goodsClick(item) {
  const url = '/pages/goods/detail'
  const id = item.id
  uni.navigateTo({
    url: `/pages/goods/detail?id=${id}`,
    success: (res) => {
      res.eventChannel.emit('acceptDataFromOpenerPage', { item })
    },
  })
}
</script>

<template>
  <!-- 搜索框 -->
  <!-- <view class="fixed-search">
    <img class="search-icon" src="/static/images/search.png" alt="搜索图标">
    <input class="search-input" type="text" placeholder="请输入搜索内容" placeholder-class="white-placeholder">
  </view> -->
  <!-- 背景图 -->
  <view class="flex flex-col">
    <view>
      <image class="h-[400rpx] w-full" :src="backImg" mode="aspectFill" />
    </view>
    <view class="wrapper relative z-100 mt-[-40rpx] flex overflow-hidden rounded-2xl">
      <!-- 左侧标签栏 -->
      <wd-sidebar v-model="active" @change="handleChange">
        <wd-sidebar-item v-for="(item, index) in category" :key="item.id" :value="index" :label="item.name.slice(0, 4)" />
      </wd-sidebar>
      <view class="content">
        <scroll-view
          scroll-y scroll-with-animation :scroll-top="scrollTop" :throttle="false"
          @scroll="onScroll"
        >
          <view v-for="(item) in category" :key="item.id" class="category">
            <wd-cell-group :title="item.name.slice(0, 4)" class="border">
              <wd-cell v-for="(cell) in item.goods" :key="cell.id" clickable title-width="0px" @click="goodsClick(cell)">
                <view class="flex justify-between">
                  <!-- 左侧图片 -->
                  <image
                    :src="BASE_URL + cell.cover"
                    class="h-24 w-24 rounded-lg" mode="aspectFill"
                  />
                  <!-- 右侧子块，设置 flex 为 3，占据 3 份宽度 -->
                  <view class="w-55%">
                    <view class="h-full flex flex-col justify-between text-left">
                      <!-- 第一行和第二行内容的容器 -->
                      <view class="flex flex-col">
                        <!-- 第一行：title -->
                        <text class="text-base font-bold">
                          {{ cell.title }}
                        </text>
                        <!-- 第二行：label -->
                        <text class="text-sm text-[#c9b09c]">
                          {{ cell.title }}
                        </text>
                      </view>
                      <!-- 第三行：price 和图标 -->
                      <view class="flex items-center justify-between">
                        <text class="text-orange-500 font-bold">
                          ¥{{ cell?.minPrice ?? '—' }}起
                        </text>
                        <image
                          class="h-5 w-5 rounded-2xl bg-[#cdb49f] p-1.5"
                          src="/static/images/shopping.png" mode="aspectFit"
                        >
                          <!-- <wd-icon
                      class="rounded-3xl bg-[#cdb49f] p-1" name="cart" size="20px"
                      color="white"
                    /> -->
                        </image>
                      </view>
                    </view>
                  </view>
                </view>
              </wd-cell>
            </wd-cell-group>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.wrapper {
  height: calc(100vh - var(--window-top) - 400rpx + 40rpx);
  // height: calc(100vh - var(--window-top) - constant(safe-area-inset-bottom) - 120rpx);
  // height: calc(100vh - var(--window-top) - env(safe-area-inset-bottom) - 120rpx);
}

.category {
  position: relative;
  box-sizing: border-box;
  /* 确保顶部没有额外间距影响滚动位置 */
  margin-top: 0;
  padding-top: 0;
}

.content {
  flex: 1;
  background: #fff;
  box-sizing: border-box;
}

/* 覆盖 .wd-cell__wrapper 的 display 属性 默认flex会造成占位  */
::v-deep .wd-cell__wrapper {
  display: block !important;
  /* 可根据需求修改为其他值，如 inline-block */
}

.fixed-search {
  position: fixed;
  z-index: 20;
  top: 100rpx;
  left: 40rpx;
  display: flex;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.3);
  /* 半透明背景 */
  border-radius: 20px;
  /* 圆角矩形 */
  padding: 5px 15px;
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  background-color: transparent;
  margin-left: 20rpx;
}

.search-icon {
  width: 40rpx;
  height: 40rpx;
}

::v-deep .white-placeholder {
  color: #fff;
  /* 设置 placeholder 文字颜色为白色 */
  font-size: 28rpx;
  /* 可选：设置字体大小 */
}

image {
  will-change: transform;
}
</style>
